﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Security.Principal;

namespace RentAWorker.Business.WebHost.Code
{
    public static class RentAWorkerGroupHelper
    {
        public static string[] GetRolesForCurrentUser(IIdentity CurrentUser)
        {
            // The following Code requires aspNetCompatibilityEnabled="true" to
            // have the Http-Context available!
            string MyPolicyFile = HttpContext.Current.Server.MapPath("~/Code/GroupMemberships.xml");

            // KNOM: Added Value.ToLower() --> Comparison should be case insensitive
            XDocument Doc = XDocument.Load(MyPolicyFile);
            var Results = from g in Doc.Descendants(XName.Get("group"))
                          where g.Parent.Attribute(XName.Get("name")).Value.ToLower().Equals(CurrentUser.Name.ToLower())
                          select g.Attribute(XName.Get("name")).Value;

            return Results.ToArray();
        }

        public static bool IsCurrentUserInRole(string roleName)
        {
            string[] Roles = GetRolesForCurrentUser
                             (
                                System.Threading.Thread.CurrentPrincipal.Identity
                             );
            bool IsInRole = Roles.Contains(roleName);
            return IsInRole;
        }
    }
}
